/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */
package es.silenus.detecta.model;

import org.springframework.context.MessageSource;

import java.util.Locale;


/**
 * Context class.
 *
 * @author <a href="mailto:malonso@silenus-consultoria.es">Mariano Alonso</a>
 *
 * @since 14-abr-2009 19:01:40
 */
public final class Context {
	/**
	 * User thread-local.
	 */
	private static final ThreadLocal<UserPrincipal> USER = new InheritableThreadLocal<UserPrincipal>();

	/**
	 * User thread-local.
	 */
	private static final ThreadLocal<MessageSource> MESSAGES = new InheritableThreadLocal<MessageSource>();

/**
   * Hidden constructor.
   */
	private Context() {
	}

	/**
	 * Sets the user.
	 *
	 * @param user the user.
	 */
	public static void setUser(final UserPrincipal user) {
		USER.set(user);
	}

	/**
	 * Retrieves the user.
	 *
	 * @return the user.
	 */
	public static UserPrincipal getUser() {
		return USER.get();
	}

	/**
	 * Sets the message source.
	 *
	 * @param messageSource the message source.
	 */
	public static void setMessageSource(final MessageSource messageSource) {
		MESSAGES.set(messageSource);
	}

	/**
	 * Retrieves the message source.
	 *
	 * @return the message source,
	 */
	public static MessageSource getMessageSource() {
		return MESSAGES.get();
	}

	/**
	 * Retrieves the locale.
	 *
	 * @return the locale.
	 */
	public static Locale getLocale() {
		UserPrincipal theUser = getUser();

		if(theUser != null) {
			return theUser.getLocale();
		}

		return Locale.getDefault();
	}
}
